package com.zhixing.user.controller;

import com.zhixing.common.annotation.Driver;
import com.zhixing.common.domain.vo.DriverInfoVO;
import com.zhixing.common.exception.ZhixingException;
import com.zhixing.common.utils.Res;
import com.zhixing.common.utils.UserContext;
import com.zhixing.user.domain.dto.AuthInfoDTO;
import com.zhixing.user.domain.vo.AuthStatusVO;
import com.zhixing.user.service.DriverService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import static com.zhixing.common.domain.enums.HttpStatus.CREDENTIALS_ALREADY_EXPIRE;

/**
 * 司机接口
 */
@Slf4j
@RestController
@RequestMapping("/driver")
@RequiredArgsConstructor
public class DriverController {

    private final DriverService driverService;

    /**
     * 获取司机认证状态
     * @return AuthStatusVO 认证状态信息
     */
    @Driver
    @GetMapping("/authStatus")
    public Res<AuthStatusVO> getDriverAuthStatus() {
        Integer userId = UserContext.getUserInfo().getId();
        log.info("用户服务调用，获取司机认证状态，用户id：{}", userId);
        return Res.ok(driverService.getDriverAuthStatus(userId));
    }

    /**
     * 创建或更新司机认证信息
     * @param authInfoDTO 认证信息
     * @return 操作结果
     */
    @Driver
    @PostMapping("/authInfo")
    public Res<Void> createOrUpdateDriverAuthInfo(@Validated @RequestBody AuthInfoDTO authInfoDTO) {
        Integer userId = UserContext.getUserInfo().getId();
        log.info("用户服务调用，创建或更新司机认证信息，用户id：{}", userId);
        if (authInfoDTO.getIdCardExpireDate().isBefore(LocalDate.now()) || authInfoDTO.getDriverLicenseExpireDate().isBefore(LocalDate.now())) throw new ZhixingException(CREDENTIALS_ALREADY_EXPIRE);
        driverService.createOrUpdateDriverAuthInfo(userId, authInfoDTO);
        return Res.ok();
    }

    /**
     * 获取司机信息
     * @param driverId 司机id
     * @return DriverInfoVO 司机信息
     */
    @GetMapping("/driverInfo/{driverId}")
    public Res<DriverInfoVO> getDriverInfo(@PathVariable Integer driverId) {
        log.info("用户服务调用，获取司机信息，司机id：{}", driverId);
        return Res.ok(driverService.getDriverInfo(driverId));
    }

    /**
     * 根据司机id获取用户id
     * @param driverId 司机id
     * @return userId 用户id
     */
    @GetMapping("/userId/{driverId}")
    public Res<Integer> getUserIdByDriverId(@PathVariable Integer driverId) {
        log.info("用户服务调用，根据司机id获取用户id，司机id：{}", driverId);
        return Res.ok(driverService.getUserIdByDriverId(driverId));
    }
}
